<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UserKeepModel extends Model
{
    protected $table = 'user_keep';
    public $timestamps = false;
    protected $guarded = [];

    //    管理User表
    public function user(){
        return $this->hasMany(UserModel::class,'id','focus_id');
    }

    public function getIsFocus($uuid,$to_uid)
    {
        $res =   UserKeepModel::where(['uid' => $uuid,'focus_id' => $to_uid]) ->get();
        if(count($res) > 0){//成功！
            return ['code' => true,'data' => 1];
        }else{
            return ['code' => false,'data' => 0];
        }
    }

    public function SaveFocusUser($uuid, $focus_id)
    {

        $res =   UserKeepModel::create([
            'focus_id' => $focus_id,
            'uid' => $uuid,
            'created_at' => date('Y-m-d H:i:s')
        ]);


        if($res){//成功！

            $user = UserModel::find($uuid);
            $user->m_keep = $user ->m_keep + 1;//我的关注数量
            $user->save();

            $user = UserModel::find($focus_id);
            $user->m_fans = $user-> m_fans +1;//我的粉丝数量
            $user->save();

            return ['code' => true,'data' => 1];
        }else{
            return ['code' => false,'data' => 0];
        }

    }

    public function deleteFocusUser($uuid, $focus_id)
    {
        $res =   DB::table('user_keep') -> where(['uid' => $uuid,'focus_id' => $focus_id]) ->delete();
        if($res){//成功！

            $user = UserModel::find($uuid);
            $user->m_keep = $user ->m_keep - 1;//我的关注数量
            $user->save();

            $user = UserModel::find($focus_id);
            $user->m_fans = $user-> m_fans  - 1;//我的粉丝数量
            $user->save();

            return ['code' => true,'data' => 1];
        }else{
            return ['code' => false,'data' => 0];
        }
    }

    public function getFocusNumDesc($uuid)
    {

        $res = UserKeepModel::with([
            'user' => function($query){
                $query ->select(['id','sex','nick_name','head_img']);
            }
        ]) ->where(['uid' => $uuid]) ->get();

        if($res){//成功！
            return ['code' => true,'data' => $res];
        }else{
            return ['code' => false,'data' => 0];
        }

    }

    public function getFansNumDesc($uuid)
    {
        $res = UserKeepModel::with([
            'user' => function($query){
                $query ->select(['id','sex','nick_name','head_img']);
            }
        ]) ->where(['focus_id' => $uuid]) ->get();

        if($res){//成功！
            return ['code' => true,'data' => $res];
        }else{
            return ['code' => false,'data' => 0];
        }
    }


}
